package com.linanqing.javademo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity implements ServiceConnection, View.OnClickListener {

    private Intent serviceIntent;
    private EditText etInput;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        serviceIntent = new Intent();
        serviceIntent.setComponent(new ComponentName("com.linanqing.aidldemo",
                "com.linanqing.aidldemo.service.TestService"));
        //   startService(serviceIntent);

        etInput = findViewById(R.id.etInput);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(this);
    }

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        iMyAidlInterface = IMyAidlInterface.Stub.asInterface(iBinder);
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        iMyAidlInterface = null;
    }

    private IMyAidlInterface iMyAidlInterface = null;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnStart:
                bindService(serviceIntent, this, Context.BIND_AUTO_CREATE);
                break;

            case R.id.btnStop:
                unbindService(this);
                iMyAidlInterface = null;
                break;

            case R.id.btnSend:
                if (null == iMyAidlInterface) {
                    break;
                }
                try {
                    iMyAidlInterface.setData(etInput.getText().toString());
                } catch (RemoteException e) {
                    e.printStackTrace();

                }
                break;
        }
    }
}